package at.codejedi.sto.model.combat;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;

@Entity
public class Battle implements IBattle {

	public static List<IBattle> createFromBattles(
			List<IPlayerBattle> playerBattles) {
		SortedMap<Long, IPlayerBattle> battlesSorted = new TreeMap<Long, IPlayerBattle>();

		for (IPlayerBattle playerBattle : playerBattles) {
			battlesSorted.put(playerBattle.getBeginningMillis(), playerBattle);
		}

		List<IPlayerBattle> lastBattles = new ArrayList<IPlayerBattle>();
		long lastMillis = 0;
		long diff = 20000;
		List<IBattle> battles = new ArrayList<IBattle>();
		for (IPlayerBattle playerBattle : battlesSorted.values()) {
			if (lastMillis != 0) {
				long beginningMillis = playerBattle.getBeginningMillis();
				if (beginningMillis - lastMillis > diff) {
					Battle battle = new Battle(lastBattles);
					battles.add(battle);
					lastBattles = new ArrayList<IPlayerBattle>();
				}
			}
			lastMillis = playerBattle.getEndingMillis();
			lastBattles.add(playerBattle);
		}
		Battle battle = new Battle(lastBattles);
		battles.add(battle);
		return battles;
	}

	public static List<IBattle> createFromPlayers(List<IPlayer> players) {
		List<IPlayerBattle> playerBattles = new ArrayList<IPlayerBattle>();
		for (IPlayer player : players) {
			playerBattles.addAll(player.getBattles());
		}
		return createFromBattles(playerBattles);
	}

	private List<IPlayerBattle> playersMap;

	private String uuid;

	private Battle(List<IPlayerBattle> playersMap) {
		this.playersMap = playersMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see at.codejedi.sto.model.combat.IBattle#getPlayersMap()
	 */
	@Override
	@OneToMany(targetEntity = PlayerBattle.class)
	@Cascade(CascadeType.ALL)
	public List<IPlayerBattle> getPlayersMap() {
		return playersMap;
	}

	@Id
	@GeneratedValue(generator = "system-uuid")
	@GenericGenerator(name = "system-uuid", strategy = "uuid")
	@Column(name = "uuid", unique = true)
	public String getUuid() {
		return uuid;
	}

	public void setPlayersMap(List<IPlayerBattle> playersMap) {
		this.playersMap = playersMap;
	}

	public void setUuid(String uuid) {
		this.uuid = uuid;
	}

}
